package com.banciyuan.bcywebview.biz.main.newdiscover.ranklist;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.DailyApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.event.EventDetailActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Card;


public class InterestRankFragment extends BaseLazyContainerFragment {
    private RequestQueue mQueue;
    private int page = 1;
    private String type;
    private List<Card> mCardList = new ArrayList<>();
    private InterestRankAdapter mIntersetRankAdapter;
    private PullToRefreashRecycleView mRefreshView;
    private RecyclerView mRecyclerView;
    private ProgressbarHelper mProgressbarHelper;
    private int rightSpace;
    private int leftSpace;
    private boolean loading = false;
    private boolean end_flag = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View viewroot = inflater.inflate(R.layout.discover_layout, container, false);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initAction();
        return viewroot;
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
        type = getArguments().getString(gotoUtil.INTENT_VALUE_ONE);
        rightSpace = UIUtils.dip2px(16, getActivity());
        leftSpace = UIUtils.dip2px(4, getActivity());
    }

    @Override
    protected void initProgressbar(View rootview) {
        View mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        mRefreshView = (PullToRefreashRecycleView) rootview.findViewById(R.id.timeline_refresh_lv);
        mRecyclerView = mRefreshView.getRefreshableView();
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int index = parent.getChildAdapterPosition(view) % 2;
                if (index == 0) {
                    outRect.right = rightSpace;
                    outRect.left = leftSpace;
                } else {
                    outRect.right = leftSpace;
                    outRect.left = rightSpace;
                }
            }

            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                c.drawColor(getResources().getColor(R.color.white));
            }
        });
        mIntersetRankAdapter = new InterestRankAdapter(getActivity(), mCardList);
        mRecyclerView.setAdapter(mIntersetRankAdapter);
    }

    @Override
    protected void initAction() {
        mRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                if (!loading) {
                    loading = true;
                    end_flag = false;
                    page = 1;
                    initData();
                }
            }
        });

        mRecyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!end_flag && !loading) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + DailyApi.getHotRank();
        List<BcyPair> bcyPairs = new ArrayList<>();
        bcyPairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        bcyPairs.add(new BcyPair(HttpUtils.LIMIT, "30"));
        bcyPairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        bcyPairs.add(new BcyPair(HttpUtils.TYPE, type));
        bcyPairs.add(new BcyPair(HttpUtils.RANK_TYPE, "tag"));
        Map<String, String> map = HttpUtils.getData(bcyPairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                        JSONObject jsonObject = new JSONObject(s);
                        List<Card> templist = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<Card>>() {
                        }.getType());
                        if (templist.isEmpty()) {
                            end_flag = true;
                        }
                        dealCardData(templist);
                        onSucc();
                    } else {
                        onError();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onError();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                onError();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        mQueue.add(requestParam);
    }

    private void dealCardData(List<Card> templist) {
        if (page == 1) {
            mCardList.clear();
            mCardList.addAll(templist);
            mIntersetRankAdapter.notifyDataSetChanged();
        } else {
            int startPos = mCardList.size();
            mCardList.addAll(templist);
            mIntersetRankAdapter.notifyItemInserted(startPos + 1);
        }
    }

    private void onSucc() {
        mProgressbarHelper.onSuccess();
        mRefreshView.onRefreshComplete();
        loading = false;
    }

    private void onError() {
        mProgressbarHelper.onFailed();
        mRefreshView.onRefreshComplete();
        loading = false;
    }
}
